<template>
  <div class="client-management-container">
    <!-- 操作区域卡片 -->
    <el-card class="operation-card" shadow="hover">
      <div class="operation-area">
        <el-button type="primary" @click="showAddModal" class="action-button">
          <i class="el-icon-plus"></i> 新增客户
        </el-button>

        <!-- 搜索区域 -->
        <div class="search-area">
          <el-input
              placeholder="客户名称"
              v-model="searchClientName"
              clearable
              prefix-icon="el-icon-user"
              class="search-input"
          ></el-input>

          <el-input
              placeholder="所属公司"
              v-model="searchEnterprise"
              clearable
              prefix-icon="el-icon-office-building"
              class="search-input"
          ></el-input>

          <el-input
              placeholder="联系电话"
              v-model="searchClientPhone"
              clearable
              prefix-icon="el-icon-mobile-phone"
              class="search-input"
          ></el-input>

          <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
              class="search-button"
          >
            搜索
          </el-button>

          <!-- 新增的重置按钮 -->
          <el-button
              type="info"
              icon="el-icon-refresh"
              @click="handleReset"
              class="search-button"
          >
            重置
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="data-card" shadow="hover">
      <el-table
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
          class="data-table"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column
            type="index"
            label="序号"
            width="120"
            align="center"
            :index="calculateIndex"
        ></el-table-column>

        <el-table-column
            prop="clientName"
            label="客户名称"
            width="220"
            align="center"
        ></el-table-column>

        <el-table-column
            prop="enterprise"
            label="所属公司"
            width="220"
            align="center"
        ></el-table-column>

        <el-table-column
            prop="clientPhone"
            label="联系电话"
            width="210"
            align="center"
        ></el-table-column>

        <el-table-column
            label="操作"
            width="390"
            align="center"
            fixed="right"
        >
          <template slot-scope="scope">
            <div class = "operation -button">
            <el-button
                @click="handleEdit(scope.row)"
                type="primary"
                size="mini"
                class="action-button"
            >
              <i class="el-icon-edit"></i> 修改
            </el-button>
            <el-button
                type="danger"
                @click="handleDelete(scope.row)"
                size="mini"
                class="action-button"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
              <el-button
                  type="primary"
                  @click="handleGoods(scope.row)"
                  size="mini"
                  class="action-button"
              >
                查看货物
              </el-button>
            </div>

          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增客户模态框 -->
    <el-dialog
        title="新增客户"
        :visible.sync="addDialogVisible"
        width="500px"
        custom-class="tech-dialog"
        :before-close="handleClose"
    >
      <el-form
          :model="addForm"
          :rules="rules"
          ref="addForm"
          label-width="100px"
          class="tech-form"
      >
        <el-form-item label="客户名称" prop="clientName">
          <el-input
              v-model="addForm.clientName"
              placeholder="请输入客户名称"
              prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属公司" prop="enterprise">
          <el-input
              v-model="addForm.enterprise"
              placeholder="请输入所属公司"
              prefix-icon="el-icon-office-building"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="clientPhone">
          <el-input
              v-model="addForm.clientPhone"
              placeholder="请输入联系电话"
              prefix-icon="el-icon-mobile-phone"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false" class="cancel-button">取消</el-button>
          <el-button type="primary" @click="submitForm" class="confirm-button">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改客户模态框 -->
    <el-dialog
        title="修改客户"
        :visible.sync="editDialogVisible"
        width="500px"
        custom-class="tech-dialog"
        :before-close="handleEditClose"
    >
      <el-form
          :model="editForm"
          :rules="rules"
          ref="editFormRef"
          label-width="100px"
          class="tech-form"
      >
        <el-form-item label="客户ID" prop="cid">
          <el-input
              v-model="editForm.cid"
              disabled
              class="disabled-input"
          ></el-input>
        </el-form-item>
        <el-form-item label="客户名称" prop="clientName">
          <el-input
              v-model="editForm.clientName"
              placeholder="请输入客户名称"
              prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属公司" prop="enterprise">
          <el-input
              v-model="editForm.enterprise"
              placeholder="请输入所属公司"
              prefix-icon="el-icon-office-building"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="clientPhone">
          <el-input
              v-model="editForm.clientPhone"
              placeholder="请输入联系电话"
              prefix-icon="el-icon-mobile-phone"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false" class="cancel-button">取消</el-button>
          <el-button type="primary" @click="submitEditForm" class="confirm-button">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看货物模态框 -->
    <el-dialog
        title="货物列表"
        :visible.sync="goodsDialogVisible"
        width="800px"
        custom-class="tech-dialog"
        :before-close="handleGoodsClose"
    >
      <el-table
          :data="goodsList"
          border
          style="width: 100%"
          v-loading="goodsLoading"
          class="data-table"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column
            prop="name"
            label="货物名称"
            width="253"
            align="center"
        ></el-table-column>
        <el-table-column
            prop="type"
            label="货物类型"
            width="253"
            align="center"
        ></el-table-column>
        <el-table-column
            prop="nowNum"
            label="货物数量"
            width="253"
            align="center"
        ></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  data() {
    return {
      tableData: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        clientName: '',
        enterprise: '',
        clientPhone: '',
        goods: {
          name: '',
          type: '',
          nowNum: 0
        }
      },
      editForm: {
        cid: '',
        clientName: '',
        enterprise: '',
        clientPhone: '',
        goods: {
          name: '',
          type: '',
          nowNum: 0
        }
      },
      rules: {
        clientName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' },
        ],
        enterprise: [
          { required: true, message: '请输入所属公司', trigger: 'blur' }
        ],
        clientPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      },
      searchClientName: '',
      searchEnterprise: '',
      searchClientPhone: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      goodsDialogVisible: false,
      goodsList: [],
      goodsLoading: false,
      currentClientId: null,
    }
  },
  mounted() {
    this.fetchUserList();
  },
  methods: {
    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchUserList();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchUserList();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchUserList();
    },
    fetchUserList() {
      this.loading = true;
      request.get('/client/clientList', {
        params: {
          page: this.currentPage,
          size: this.pageSize,
          clientName: this.searchClientName,
          enterprise: this.searchEnterprise,
          clientPhone: this.searchClientPhone,
        }
      })
          .then(response => {
            this.tableData = response.data.data.clientList.list;
            this.total = response.data.data.clientList.total;
            this.loading = false;
          })
          .catch(error => {
            console.error('获取客户列表失败:', error);
            this.$message.error('获取客户列表失败');
            this.loading = false;
          });
    },
    showAddModal() {
      this.addForm = {
        clientName: '',
        enterprise: '',
        clientPhone: '',
        goods: {
          name: '',
          type: '',
          nowNum: 0
        }
      };
      this.addDialogVisible = true;
    },
    handleEdit(row) {
      this.editForm = {
        cid: row.cid,
        clientName: row.clientName,
        enterprise: row.enterprise,
        clientPhone: row.clientPhone,
        goods: {
          name: row.goods?.name || '',
          type: row.goods?.type || '',
          nowNum: row.goods?.nowNum || 0
        }
      };
      this.editDialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('确定要删除该客户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'tech-message-box'
      }).then(() => {
        request.delete('/client/deleteClient', {
          params: {
            id: row.cid
          }
        })
            .then(() => {
              this.$message.success('删除成功');
              this.fetchUserList();
            })
            .catch(error => {
              console.error('删除失败:', error);
              this.$message.error('删除失败');
            });
      }).catch(() => {});
    },
    handleClose(done) {
      this.$confirm('确定要关闭吗？未保存的内容将会丢失', '提示', {
        type: 'warning',
        customClass: 'tech-message-box'
      }).then(() => {
        done();
      }).catch(() => {});
    },
    handleEditClose(done) {
      this.$confirm('确定要关闭吗？未保存的内容将会丢失', '提示', {
        type: 'warning',
        customClass: 'tech-message-box'
      }).then(() => {
        done();
      }).catch(() => {});
    },
    submitForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          request.post(`/client/addClient/`, this.addForm)
              .then(() => {
                this.$message.success('新增客户成功');
                this.addDialogVisible = false;
                this.fetchUserList();
              })
              .catch(error => {
                console.error('新增客户失败:', error);
                this.$message.error('新增客户失败');
              });
        }
      });
    },
    submitEditForm() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          const updateData = {
            cid: this.editForm.cid,
            clientName: this.editForm.clientName,
            enterprise: this.editForm.enterprise,
            clientPhone: this.editForm.clientPhone
          };
          request.put(`/client/updateClient`, updateData)
              .then(() => {
                this.$message.success('修改客户成功');
                this.editDialogVisible = false;
                this.fetchUserList();
              })
              .catch(error => {
                console.error('修改客户失败:', error);
                this.$message.error('修改客户失败');
              });
        }
      });
    },
    handleGoods(row) {
      this.currentClientId = row.cid;
      this.goodsDialogVisible = true;
      this.fetchGoodsList();
    },
    handleGoodsClose(done) {
      this.$confirm('确定要关闭吗？', '提示', {
        type: 'warning',
        customClass: 'tech-message-box'
      }).then(() => {
        this.goodsList = [];
        this.currentClientId = null;
        done();
      }).catch(() => {});
    },
    fetchGoodsList() {
      this.goodsLoading = true;
      request.get('/client/getGoodsList', {
        params: {
          id: this.currentClientId
        }
      })
          .then(response => {
            if (response.data.code === '200') {
              this.goodsList = response.data.data.clientGoods
                  .filter(item => item?.goods)
                  .map(item => ({
                    name: item.goods.name,
                    type: item.goods.type,
                    nowNum: item.goods.nowNum
                  }));
            } else {
              this.$message.error(response.data.msg || '获取货物列表失败');
            }
            this.goodsLoading = false;
          })
          .catch(error => {
            console.error('获取货物列表失败:', error.response || error);
            this.$message.error(error.response?.data?.msg || '获取货物列表失败');
            this.goodsLoading = false;
          });
    },
    handleReset() {
      this.searchClientName = '';
      this.searchEnterprise= '';
      this.searchClientPhone = '';
      this.currentPage = 1;
      this.fetchUserList();
    }
  }
}
</script>

<style scoped>
.client-management-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 80px);
}

.operation-card {
  margin-bottom: 20px;
  border-radius: 8px;
  border: none;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.operation -buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.data-card {
  border-radius: 8px;
  border: none;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.operation-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.search-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-input {
  width: 180px;
}

.search-button {
  margin-left: 10px;
}

.search-button {
  margin-left: 10px;
  transition: all 0.3s;
  border-radius: 4px;
}

.search-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(58, 123, 213, 0.2);
}

.action-button {
  transition: all 0.3s;
  border-radius: 4px;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(58, 123, 213, 0.2);
}

.data-table {
  margin-top: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/deep/ .tech-dialog {
  border-radius: 8px;
  background: linear-gradient(145deg, #f5f7fa, #e4e7ed);
  border: 1px solid rgba(58, 123, 213, 0.2);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

/deep/ .tech-dialog .el-dialog__header {
  background: linear-gradient(90deg, #3a7bd5, #00d2ff);
  border-radius: 8px 8px 0 0;
  padding: 15px 20px;
}

/deep/ .tech-dialog .el-dialog__title {
  color: white;
  font-weight: 600;
}

/deep/ .tech-dialog .el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.tech-form {
  padding: 20px;
}

/deep/ .tech-form .el-input__inner {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
}

/deep/ .tech-form .el-input__inner:hover {
  border-color: #c0c4cc;
}

/deep/ .tech-form .el-input__inner:focus {
  border-color: #3a7bd5;
  box-shadow: 0 0 0 2px rgba(58, 123, 213, 0.2);
}

.disabled-input /deep/ .el-input__inner {
  background-color: #f5f7fa;
  color: #909399;
  cursor: not-allowed;
}

.cancel-button {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  color: #606266;
  transition: all 0.3s;
}

.cancel-button:hover {
  background-color: #e4e7ed;
  border-color: #c0c4cc;
  color: #606266;
}

.confirm-button {
  background: linear-gradient(90deg, #3a7bd5, #00d2ff);
  border: none;
  transition: all 0.3s;
}

.confirm-button:hover {
  background: linear-gradient(90deg, #2c5fb3, #00b7e6);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(58, 123, 213, 0.3);
}

/deep/ .tech-message-box {
  border-radius: 8px;
  background: linear-gradient(145deg, #f5f7fa, #e4e7ed);
  border: 1px solid rgba(58, 123, 213, 0.2);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

/deep/ .tech-message-box .el-message-box__header {
  background: linear-gradient(90deg, #3a7bd5, #00d2ff);
  border-radius: 8px 8px 0 0;
  padding: 15px 20px;
}

/deep/ .tech-message-box .el-message-box__title {
  color: white;
  font-weight: 600;
}

/deep/ .tech-message-box .el-message-box__content {
  padding: 20px;
}

/deep/ .tech-message-box .el-message-box__btns {
  padding: 10px 20px 20px;
}
</style>